# app/audio/tts.py
import os
import tempfile
from pathlib import Path
import threading

class TextToSpeech:
    """文字转语音类"""
    
    def __init__(self):
        self.available = False
        try:
            # 尝试导入pyttsx3库
            import pyttsx3
            self.engine = pyttsx3.init()
            self.available = True
            self._setup_engine()
            # 添加锁以防止并发访问冲突
            self.lock = threading.Lock()
            # 当前是否正在播报
            self.is_speaking = False
        except ImportError:
            print("警告: 未找到pyttsx3库，文字转语音功能将被禁用")
    
    def _setup_engine(self):
        """设置TTS引擎的参数"""
        if not self.available:
            return
            
        # 设置语速和音量
        self.engine.setProperty('rate', 150)    # 语速，默认值为200
        self.engine.setProperty('volume', 0.8)  # 音量，范围为0.0到1.0
        
        # 获取可用的声音
        voices = self.engine.getProperty('voices')
        
        # 尝试设置中文声音，如果找不到则使用默认声音
        chinese_voice = None
        for voice in voices:
            if 'chinese' in voice.name.lower() or 'zh' in voice.id.lower():
                chinese_voice = voice
                break
                
        if chinese_voice:
            self.engine.setProperty('voice', chinese_voice.id)
    
    def is_available(self):
        """检查TTS功能是否可用"""
        return self.available
    
    def _speak_thread(self, text):
        """在单独的线程中执行语音播报"""
        with self.lock:
            self.is_speaking = True
            try:
                self.engine.say(text)
                self.engine.runAndWait()
            except Exception as e:
                print(f"文字转语音过程中发生错误: {e}")
            finally:
                self.is_speaking = False
    
    def speak(self, text):
        """将文本转换为语音并播放（非阻塞方式）"""
        if not self.available:
            print("文字转语音功能不可用，请安装pyttsx3库")
            return False
            
        # 如果当前已经在播报，不启动新的播报
        if hasattr(self, 'is_speaking') and self.is_speaking:
            return False
            
        # 在新线程中执行语音播报
        threading.Thread(target=self._speak_thread, args=(text,), daemon=True).start()
        return True
    
    def save_to_file(self, text, output_path=None):
        """将文本转换为语音并保存为文件"""
        if not self.available:
            print("文字转语音功能不可用，请安装pyttsx3库")
            return None
            
        if output_path is None:
            # 如果没有指定输出路径，创建临时文件
            fd, output_path = tempfile.mkstemp(suffix='.mp3')
            os.close(fd)
            
        try:
            self.engine.save_to_file(text, output_path)
            self.engine.runAndWait()
            return output_path
        except Exception as e:
            print(f"保存语音文件时发生错误: {e}")
            return None